import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";

//创建axios实例
const service = axios.create({
  //配置基地址
  baseURL: process.env.VUE_APP_BASE_API, //基地址
  // withCredentials: true, // send cookies when cross-domain requests
  //配置超时时间
  timeout: 10000, // request timeout
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    if (store.getters.token) {
      config.headers["Authorization"] = `Bearer ${store.getters.token}`;
    }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// 响应拦截器
// service.interceptors.response.use(响应成功方法,响应失败的方法
service.interceptors.response.use(
  (response) => {
    console.log("响应成功", response);
    const { code, data, message, success } = response.data;
    if (success) {
      return data;
    } else {
      //提示报错信息
      Message({ type: "error", message: message });
      return Promise.reject(message);
    }
  },
  (error) => {
    console.log("响应失败", error);
  }
);

export default service;
